package com.firmboy.thread;

import com.firmboy.db.DBHelper;
import org.junit.Test;
import sun.jvm.hotspot.oops.ObjectHeap;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.lang.reflect.Array;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 演示线程中的join方法的作用
 *
 * @author firmboy
 * @create 2018-04-13 下午9:56
 **/
public class JoinTest {


    @Test
    public void mushThread(){
        //计算中的执行时间
        long start = System.currentTimeMillis();

        //分页数量
        int pageSize = 10000;
        Map<String, Object> obj = DBHelper.getMapObject("select count(*) NUM from account", new Object[]{});
        int count = Integer.valueOf(obj.get("NUM").toString());

        int page = 0;
        if(count%pageSize==0){
            page = count/pageSize;
        }else{
            page = count/pageSize+1;
        }

        //创建路径名
        URL resource = DBHelper.class.getResource("/");
        String path = resource.getPath();
        int target = path.lastIndexOf("target");
        path = path.substring(0, target);
        path=path+"src/main/java/com/firmboy/thread";
        String fileName = "test";

        //创建一个文件


        try{
            final Map<String, String> map = new HashMap<>();
            List<Thread> list = new ArrayList<Thread>();
            for (int i = 0;i<page;i++){
                map.put("path",path);
                map.put("fileName",fileName);
                map.put("pageSize",pageSize+"");

                Thread worker = new Thread(new Runnable() {
                    @Override
                    public void run() {
                        //System.out.println(map.get("i")+"文件生成成功");
                        createFile(map);
                        System.out.println(Thread.currentThread().getName()+"文件生成");
                    }
                });
                worker.setName(i+"");


                worker.start();
                list.add(worker);
            }

            for (Thread worker:list
                 ) {
                worker.join();
            }


        }catch(Exception e){
            e.printStackTrace();
        }finally {

            long end = System.currentTimeMillis();
            System.out.println("共耗时："+(end-start)+"毫秒");
        }



    }


    @Test
    public void oneThread(){
        //计算中的执行时间
        long start = System.currentTimeMillis();

        //分页数量
        int pageSize = 10000;
        Map<String, Object> obj = DBHelper.getMapObject("select count(*) NUM from account", new Object[]{});
        int count = Integer.valueOf(obj.get("NUM").toString());

        int page = 0;
        if(count%pageSize==0){
            page = count/pageSize;
        }else{
            page = count/pageSize+1;
        }

        //创建路径名
        URL resource = DBHelper.class.getResource("/");
        String path = resource.getPath();
        int target = path.lastIndexOf("target");
        path = path.substring(0, target);
        path=path+"src/main/java/com/firmboy/thread";
        String fileName = "test";

        //创建一个文件
        FileWriter fw = null;

        try{

            StringBuffer sb = new StringBuffer();
            String str = "";
            List<Map<String, Object>> list = new ArrayList<Map<String,Object>>();
            for (int i = 0;i<page;i++){
                File file = new File(path+"/"+fileName+i+".txt");
                if(file.exists()){
                    file.delete();
                }
                fw = new FileWriter(file);
                list = DBHelper.getListObject("select * from account limit ?,?", new Object[]{i*pageSize,pageSize});
                System.out.println(list.size());
                for (Map<String,Object> map:list
                        ) {
                    sb = new StringBuffer();
                    for (Map.Entry<String,Object> entry:map.entrySet()
                            ) {
                        sb.append(entry.getKey()+":"+entry.getValue().toString()+",");
                    }
                    str = sb.toString();
                    sb = null;
                    str = str.substring(0, str.length() - 1);
                    fw.append(str+"/r/n");
                    str = null;
                }
            }
        }catch(Exception e){
            e.printStackTrace();
        }finally {

            long end = System.currentTimeMillis();
            System.out.println("共耗时："+(end-start)+"毫秒");
        }
    }


    private void createFile(Map<String,String> param){
        String path = param.get("path");
        String fileName = param.get("fileName");
        int i  = Integer.valueOf(Thread.currentThread().getName());
        System.out.println("当前i:"+i);
        int pageSize = Integer.valueOf(param.get("pageSize"));


        FileWriter fw = null;
        StringBuffer sb = new StringBuffer();
        String str = "";
        List<Map<String, Object>> list = new ArrayList<Map<String,Object>>();
        try {
            File file = new File(path+"/"+fileName+i+".txt");
            if(file.exists()){
                file.delete();
            }
            fw = new FileWriter(file);
            list = DBHelper.getListObject("select * from account limit ?,?", new Object[]{i*pageSize,pageSize});
            System.out.println(list.size());
            for (Map<String,Object> map:list
                    ) {
                sb = new StringBuffer();
                for (Map.Entry<String,Object> entry:map.entrySet()
                        ) {
                    sb.append(entry.getKey()+":"+entry.getValue().toString()+",");
                }
                str = sb.toString();
                sb = null;
                str = str.substring(0, str.length() - 1);
                fw.append(str+"\r\n");
                str = null;
            }
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            if(fw!=null){
                try {
                    fw.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }


    @Test
    public void joinTest() throws InterruptedException {

        int count = 10;

        ArrayList<Thread> workers = new ArrayList<>();



        for(int i=0;i<count;i++){

            Thread worker = new Thread(new Runnable() {
                @Override
                public void run() {
                    try {
                        Thread.sleep(5000L);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    System.out.println("现在是第"+Thread.currentThread().getName()+"个线程");
                }
            });
            worker.setName(i+"");
            worker.start();
            workers.add(worker);
        }

        for (Thread worker:workers
             ) {
            worker.join();
        }

        System.out.println("线程都已执行完毕");



    }

}
